package com.atguigu.eduservice.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期操作工具类
 *
 * @author qy
 * @since 1.0
 */
@Slf4j
public class DateUtil {

    private static final String dateFormat = "yyyy-MM-dd";
    private static final String filedateFormat = "yyyy/MM/dd";
    /**
     * 文件格式化日期
     *
     *
     */
    public static String fileformatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(filedateFormat);
        return sdf.format(date);

    }

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.format(date);

    }
    public static String formatDate_spec(Date date,String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);

    }
    public static void copylogfile() throws IOException{
        String path=System.getProperty("user.dir");
        String rq_z = DateUtil.formatDate(DateUtil.addDays(new Date(),-1));
        String filepath=path+"\\invoice\\info\\log_invoice_"+rq_z+".log";
        File source=new File(path+"\\invoice\\log_invoice.log");
        File dest = new File(filepath);
//        if (source.exists()){
//            log.info(source.toString());
//        }
        if ((!dest.exists())&&(source.exists())) {
            log.info("将文件"+source.getName()+"拷贝到"+dest.toString());
            InputStream input = null;
            OutputStream output = null;
            try {
                try {
                    input = new FileInputStream(source);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    output = new FileOutputStream(dest);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                byte[] buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buf)) > 0) {
                    output.write(buf, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                input.close();
                output.close();
            }
        };
        // if !file.ex;
    }

    /**
     * 在日期date上增加amount天 。
     *
     * @param date   处理的日期，非null
     * @param amount 要加的天数，可能为负数
     */
    public static Date addDays(Date date, int amount) {
        Calendar now =Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE,now.get(Calendar.DATE)+amount);
        return now.getTime();
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.formatDate(new Date()));
        System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
    }
}
